package com.wxg.tuan.service.impl;

import com.wxg.tuan.mapper.EmployeeMapper;
import com.wxg.tuan.mapper.UserMapper;
import com.wxg.tuan.pojo.entity.EmailLogin;
import com.wxg.tuan.result.Result;
import com.wxg.tuan.service.UserService;
import com.wxg.tuan.utill.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    //发送邮箱
    private MailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public Result sendEmail(String email) {
        SimpleMailMessage smg = new SimpleMailMessage();

        EmailLogin emailLogin =userMapper.getByEmail(email);
        if (emailLogin==null){
            return Result.error("用户不存在");
        }
        //随机六位数验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        smg.setText("验证码："+code);
        smg.setFrom(fromEmail);
        smg.setTo(email);
        smg.setSubject("登入验证码");
        redisTemplate.opsForValue().set(email,code,60, TimeUnit.SECONDS);
        mailSender.send(smg);


        return Result.success();

    }

    //邮箱登入
    @Override
    public Result emailLogin(String email, String code) {
        EmailLogin employeeEmail = userMapper.getByEmail(email);
        if (employeeEmail==null){
            return Result.error("用户不存在");
        }
        String redisCode = (String) redisTemplate.opsForValue().get(email);
//       if (!redisTemplate.hasKey(redisCode)){
//           return Result.error("key已经过期或者不存在");
//       }
        if (!redisCode.equals(code)){
            return Result.error("验证码不正确，请重新输入");
        }


        String token = JwtUtils.generateToken(employeeEmail);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        map.put("Email",employeeEmail.getEmail());


        return Result.success(map);
    }


}
